﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AppDataStruct;
using System.IO;
using System.Reflection;
using LogLib;
using System.Runtime.InteropServices;
using Aspose.Cells.Rendering;
using Aspose.Cells;

namespace PrintExcel
{
    public class PaperPrinting
    {
        private string _error = "";
        public string ErrorMessage
        {
            get { return _error; }
        }

        public string AssemblyDirectory
        {
            get
            {
                string directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
                directory = directory.Substring(6);
                return directory;
            }
        }

        private bool _bInited = false;
        public bool Inited
        {
            get { return _bInited; }
        }
        private ExcelData _reader = null;

        private WriteData _writer = null;

        public PaperPrinting()
        {

        }

        public bool Init()
        {
            _reader = new ExcelData();
            _writer = new WriteData(_reader);
            if (!_reader.LoadConfig())
            {
                _error = _reader.ErrorMessage;
                Log.WriteAsync(_reader.ErrorMessage);
                return false;
            }
            if (!_writer.Init())
            {
                _error = _writer.ErrorMessage;
                Log.WriteAsync(_writer.ErrorMessage);
                return false;
            }
            _bInited = true;
            return true;
        }

        public bool OnPrepared(SFZInfo sfzInfo, PreApplyInfo appInfo)
        {
            Log.WriteAsync($"身份证正面文件：{sfzInfo.SFZZM}，身份证背面文件：{sfzInfo.SFZBM}");
            if (!string.IsNullOrEmpty(sfzInfo.SFZZM) && File.Exists(sfzInfo.SFZZM))
                appInfo.SFZZM = sfzInfo.SFZZM;
            if (!string.IsNullOrEmpty(sfzInfo.SFZBM) && File.Exists(sfzInfo.SFZBM))
                appInfo.SFZBM = sfzInfo.SFZBM;
            Log.WriteAsync($"身份证正面文件2：{appInfo.SFZZM}，身份证背面文件：{appInfo.SFZBM}");
            return _writer.WriteExcelData(sfzInfo, appInfo);
        }

        public bool DoPrint(out string msg)
        {
            msg = "";
            try
            {
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(_writer.DestFile);
                //Get the worksheet to be printed
                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];
                Aspose.Cells.PageSetup pageSetup = worksheet.PageSetup;
                pageSetup.Orientation = PageOrientationType.Portrait;
                pageSetup.PrintGridlines = false;
                //pageSetup.
                //pageSetup.FitToPagesWide = 1;
                //pageSetup.FitToPagesTall = 2;

                pageSetup.IsHFAlignMargins = true;
                //pageSetup.LeftMargin = 1;
                //pageSetup.RightMargin = 1;
                //pageSetup.TopMargin = 0.1;
                //pageSetup.BottomMargin = 0.1;
                pageSetup.PaperSize = PaperSizeType.PaperA4;
                //pageSetup.BottomMargin = 0.3;
                //pageSetup.PrintArea = "A2:J29";
                //Apply different Image / Print options.
                Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions();

                //Set the Printing page property
                options.PrintingPage = PrintingPageType.IgnoreStyle;
                //Render the worksheet
                SheetRender sr = new SheetRender(worksheet, options);
                System.Drawing.Printing.PrinterSettings printSettings = new System.Drawing.Printing.PrinterSettings();
                printSettings.PrinterName = _reader.Printer.Printer;

                //printSettings.FromPage = 1;
                //printSettings.ToPage = 2;
                //printSettings.CanDuplex = true;
                sr.ToPrinter(printSettings.PrinterName);
                Log.WriteAsync("文件打印成功:" + _writer.DestFile);
                return true;
            }
            catch (Exception ex)
            {
                msg = ex.ToString();
                return false;
            }
        }

        //private void DoPrint()
        //{
        //    string excelFile = textBoxSourceFile.Text;
        //    Microsoft.Office.Interop.Excel.Application application = new Microsoft.Office.Interop.Excel.Application();
        //    application.Visible = false;
        //    //application.DisplayAlerts = true;
        //    Microsoft.Office.Interop.Excel.Workbook workBook = application.Workbooks.Open(excelFile, Type.Missing, Type.Missing,
        //      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
        //      Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        //    Microsoft.Office.Interop.Excel.Worksheet workSheet = workBook.Worksheets[1];

        //    //------------------------打印页面相关设置--------------------------------          
        //    workSheet.PageSetup.Zoom = false; //打印时页面设置,必须设置为false,页高,页宽才有效
        //    workSheet.PageSetup.FitToPagesWide = 1; //设置页面缩放的页宽为1页宽
        //    workSheet.PageSetup.FitToPagesTall = false; //设置页面缩放的页高自动           
        //    workSheet.PrintOutEx(); //直接打印
        //    workBook.Close(); //关闭工作空间
        //    application.Quit(); //退出程序
        //    //workSheet.SaveAs(filePath); //另存表
        //    KillProcess(application); //杀掉生成的进程    
        //    GC.Collect(); //垃圾回收机制
        //}

        [DllImport("User32.dll")]
        public static extern int GetWindowThreadProcessId(IntPtr Hwnd, out int PID);
        /// <summary>
        /// 杀掉生成的进程
        /// </summary>
        /// <param name="AppObject">进程程对象</param>
        //private static void KillProcess(Microsoft.Office.Interop.Excel.Application AppObject)
        //{
        //    int Pid = 0;
        //    IntPtr Hwnd = new IntPtr(AppObject.Hwnd);
        //    System.Diagnostics.Process p = null;
        //    try
        //    {
        //        GetWindowThreadProcessId(Hwnd, out Pid);
        //        p = System.Diagnostics.Process.GetProcessById(Pid);
        //        if (p != null)
        //        {
        //            p.Kill();
        //            p.Dispose();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Diagnostics.Debug.WriteLine("进程关闭失败！异常信息：" + ex);
        //    }
        //}

    }
}


//workSheet.PageSetup.PaperSize = Microsoft.Office.Interop.Excel.XlPaperSize.xlPaperA4;//纸张大小
//workSheet.PageSetup.Orientation = Microsoft.Office.Interop.Excel.XlPageOrientation.xlLandscape;//页面横向
//workSheet.PageSetup.Zoom = 75; //打印时页面设置,缩放比例百分之几
//workSheet.PageSetup.CenterFooter = "第 &P 页，共 &N 页";//页面下标
//workSheet.PageSetup.PrintGridlines = true; //打印单元格网线
//workSheet.PageSetup.TopMargin = 1.5 / 0.035; //上边距为2cm（转换为in）
//workSheet.PageSetup.BottomMargin = 1.5 / 0.035; //下边距为1.5cm
//workSheet.PageSetup.LeftMargin = 2 / 0.035; //左边距为2cm
//workSheet.PageSetup.RightMargin = 2 / 0.035; //右边距为2cm
//workSheet.PageSetup.CenterHorizontally = true; //文字水平居中
//application.ActivePrinter = "Microsoft Print to PDF";
//workSheet.PrintPreview(); //打印预览
